package main

import (
	"fmt"
	"time"

	//一定要导入mysql驱动，否则会报错
	_ "github.com/go-sql-driver/mysql"
	"xorm.io/xorm"
)

var engine *xorm.Engine

func main() {
	//数据库连接基本信息
	var (
		userName  string = "root"
		password  string = "root"
		ipAddress string = "127.0.0.1"
		port      int    = 3306
		dbName    string = "demo"
		charset   string = "utf8mb4"
	)
	//构建数据库连接信息
	//root:123456@tcp(127.0.0.1:3306)/go_test?charset=utf8mb4
	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", userName, password, ipAddress, port, dbName, charset)

	//fmt.Println("dataSourceName=", dataSourceName)
	var err error
	engine, err = xorm.NewEngine("mysql", dataSourceName)
	if err != nil {
		fmt.Println("数据库连接失败")
	}

	//结构体字段与数据库中表的字段对应【底层会做大小写转换处理】
	type User struct {
		Id       int64     `xorm:"id pk autoincr"`
		Name     string    `xorm:"name"`
		Salt     string    `xorm:"salt"`
		Age      int       `xorm:"age"`
		Password string    `xorm:"varchar(200) 'password'"`
		Created  time.Time `xorm:"created"`
		Updated  time.Time `xorm:"updated"`
	}

	fmt.Println(engine)

	//直接通过结构体，在数据库中创建对应的表【同步结构体与数据表】
	err = engine.Sync(new(User))
	if err != nil {
		fmt.Println("表结构同步失败")
	}

	//1. 插入单行数据
	//engine.Insert()插入对象，返回值：受影响的行数
	user := User{Name: "jack", Age: 18, Password: "123456"}
	//Insert这里应该传入一个地址
	n, err := engine.Insert(&user)
	if n >= 1 {
		fmt.Println("数据插入成功")
	} else {
		fmt.Println(err.Error())
	}

}
